import {_decorator, CCBoolean, CCInteger, Collider2D, Component, Contact2DType, IPhysics2DContact, Vec3} from 'cc';
import {EnemyController} from "db://assets/scripts/EnemyController";

const {ccclass, property} = _decorator;

@ccclass('BulletController')
export class BulletController extends Component {

    /**
     * 子弹的速度【一般是和屏幕高度一致】
     */
    @property(CCInteger)
    speed: number = 800;

    /**
     * 已销毁
     */
    @property(CCBoolean)
    destroyed: boolean = false;

    start() {
        // 注册单个碰撞体的回调函数
        let collider = this.getComponent(Collider2D);
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }

    /**
     * 开始碰撞
     *
     * @param selfCollider 自己
     * @param otherCollider 敌人
     * @param contact 碰撞信息
     */
    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 当与敌人发送碰撞时
        if (otherCollider.tag === 2){
            // 销毁敌人
            otherCollider.getComponent(EnemyController).die();
            // 销毁自己
            this.die();
        }
    }

    update(deltaTime: number) {
        // 销毁
        if (this.destroyed) {
            this.node.destroy();
            return;
        }

        // 移动
        this.node.setWorldPosition(new Vec3(this.node.worldPosition.x, this.node.worldPosition.y + this.speed * deltaTime));
        // 屏幕外销毁
        if (this.node.position.y > 820) {
            // 销毁
            this.destroyed = true;
            return;
        }
    }

    /**
     * 销毁
     */
    die() {
        // 当未销毁时
        if (!this.destroyed) {
            // 已销毁
            this.destroyed = true;
        }
    }
}

